package floappcontest.core.backbeans;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.faces.context.FacesContext;

import org.apache.myfaces.custom.fileupload.UploadedFile;

/**
 * This is a managed bean with request scope representing an uploaded file.
 * @author 
 *
 */
public class FileUpload {

	private static final String FAILED = "FAILED"; //$NON-NLS-1$

	private static final String OK = "OK"; //$NON-NLS-1$

	private UploadedFile upFile;

	private String fileName;

	public FileUpload() {
		// Default empty constructor
	}

	public UploadedFile getUpFile() {
		return this.upFile;
	}

	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}

	/**
	 * @return
	 * @throws IOException
	 */
	public String upload() throws IOException {
		String fileSeparator = System.getProperty("file.separator");
		try {
			final int bufferSize = 1000;
			InputStream inStream = getUpFile().getInputStream();
			
			String str = getUpFile().getName();
			String[] file = str.split(fileSeparator+fileSeparator);
			str = file[file.length-1];
			this.fileName = str; 
			File f = new File(".."+fileSeparator+"forms"+fileSeparator+this.fileName);
			FileOutputStream fouts = new FileOutputStream(f);
			byte[] buffer = new byte[bufferSize];
			int readCount = 0;
			while ((readCount = inStream.read(buffer)) != -1){
				if (readCount < bufferSize) {
					fouts.write(buffer, 0, readCount);
				} else {
					fouts.write(buffer);
				}
			}			
			fouts.close();
			return OK;
		} catch (IOException ioe) {
			System.out.println("File Upload Unsuccessful.");
			return FAILED;
		}


	}

	public boolean isUploaded() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		return facesContext.getExternalContext().getApplicationMap().get(
		"fileupload_bytes") != null;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}



}